package com.wj.facedetect.commom;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.os.Bundle;

import java.util.List;

/**
 * Created by tangkun on 2017/11/20.
 * 添加应用切换到前后台回调
 */

public abstract class BaseApplication extends Application {
    private boolean isCurrentRunningForeground = true;

    @Override
    public void onCreate() {
        super.onCreate();
        registerActivityLifecycleCallbacks();
    }

    /**
     * 应用切换到前台
     */
    public abstract void onApplicationForeground();

    /**
     * 应用切换到后台
     */
    public abstract void onApplicatoinBackground();

    /**
     * 注册监听Activity生命周期，用于判断应用切换至前后台
     */
    private void registerActivityLifecycleCallbacks() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

            }

            @Override
            public void onActivityStarted(Activity activity) {
                //
                if (!isCurrentRunningForeground) {
                    //应用切换至前台
                    onApplicationForeground();
                }
            }

            @Override
            public void onActivityResumed(Activity activity) {

            }

            @Override
            public void onActivityPaused(Activity activity) {

            }

            @Override
            public void onActivityStopped(Activity activity) {
                //
                isCurrentRunningForeground = isRunningForeground();
                if (!isCurrentRunningForeground) {
                    //应用切换至后台
                    onApplicatoinBackground();
                }
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {

            }
        });
    }

    /**
     * 当前应用是否在前台运行
     *
     * @return
     */
    public boolean isRunningForeground() {
        ActivityManager atyMgr = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcessInfos = atyMgr.getRunningAppProcesses();
        String applicationProcessName = getApplicationInfo().processName;
        for (ActivityManager.RunningAppProcessInfo appProcessInfo : appProcessInfos) {
            int importance = appProcessInfo.importance;
            String processName = appProcessInfo.processName;
            if (importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && processName.equals(applicationProcessName)) {
                return true;
            }
        }
        return false;
    }
}
